package com.example.lets;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lets.R;

import cn.bmob.im.BmobChat;
import cn.bmob.im.BmobChatManager;
import cn.bmob.im.BmobNotifyManager;
import cn.bmob.im.BmobRecordManager;
import cn.bmob.im.BmobUserManager;
import cn.bmob.im.bean.BmobChatUser;
import cn.bmob.im.bean.BmobInvitation;
import cn.bmob.im.bean.BmobMsg;
import cn.bmob.im.config.BmobConfig;
import cn.bmob.im.db.BmobDB;
import cn.bmob.im.inteface.EventListener;
import cn.bmob.im.util.BmobLog;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.PushListener;
import ui.MessageChatAdapter;
import ui.MyMessageReceiver;
import ui.XListView;
import util.EmoticonsEditText;
import util.HeaderLayout;



@SuppressLint({ "ClickableViewAccessibility", "InflateParams" })
public class ChatActivity extends Activity implements OnClickListener,
        XListView.IXListViewListener, EventListener {


    BmobUserManager userManager;
    BmobChatManager manager;

    String avatar;


    protected HeaderLayout mHeaderLayout;


    /**
     * ֻ����߰�ť��Title initTopBarLayout
     *
     * @throws
     */
    public void initTopBarForLeft(String titleName) {
        mHeaderLayout = (HeaderLayout)findViewById(R.id.common_actionbar);
        mHeaderLayout.init(HeaderLayout.HeaderStyle.TITLE_DOUBLE_IMAGEBUTTON);
        mHeaderLayout.setTitleAndLeftImageButton(titleName,
                R.drawable.base_action_bar_back_bg_selector,
                new OnLeftButtonClickListener());
    }
    // ��߰�ť�ĵ���¼�
    public class OnLeftButtonClickListener implements
            HeaderLayout.onLeftImageButtonClickListener {

        @Override
        public void onClick() {
            finish();
        }
    }
    Toast mToast;

    public void ShowToast(final String text) {
        if (!TextUtils.isEmpty(text)) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    if (mToast == null) {
                        mToast = Toast.makeText(getApplicationContext(), text,
                                Toast.LENGTH_LONG);
                    } else {
                        mToast.setText(text);
                    }
                    mToast.show();
                }
            });

        }
    }

    public void ShowToast(final int resId) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (mToast == null) {
                    mToast = Toast.makeText(ChatActivity.this.getApplicationContext(), resId,
                            Toast.LENGTH_LONG);
                } else {
                    mToast.setText(resId);
                }
                mToast.show();
            }
        });
    }


    public void ShowLog(String msg){
        Log.i("life",msg);
    }

    /** ���������
     * hideSoftInputView
     * @Title: hideSoftInputView
     * @Description: TODO
     * @param
     * @return void
     * @throws
     */
    public void hideSoftInputView() {
        InputMethodManager manager = ((InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE));
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    //----
    private Button btn_chat_emo, btn_chat_send, btn_chat_add,btn_chat_keyboard, /*btn_speak,*/ btn_chat_voice;

    XListView mListView;

    EmoticonsEditText edit_user_comment;

    String targetId;

    BmobChatUser targetUser = new BmobChatUser();

    private static int MsgPagerNum;

    private LinearLayout layout_more, layout_emo, layout_add;


    private TextView tv_picture, tv_camera, tv_location;



    BmobRecordManager recordManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        targetId = getIntent().getStringExtra("targetId");
        setContentView(R.layout.activity_chat);
        BmobChat.DEBUG_MODE = true;

        BmobChat.getInstance(this).init("13f0e49d5141ecd8ba0aa06f484e7e34");
        manager = BmobChatManager.getInstance(this);
        MsgPagerNum = 0;

        targetUser.setObjectId(targetId);

        initNewMessageBroadCast();
        initView();
    }

    private void initRecordManager(){
        recordManager = BmobRecordManager.getInstance(this);

    }

    private void initView() {
        mHeaderLayout = (HeaderLayout) findViewById(R.id.common_actionbar);
        mListView = (XListView) findViewById(R.id.mListView);
        initTopBarForLeft("与" + getIntent().getStringExtra("nickname") + "聊天中");
        initBottomView();
        initXListView();
        initVoiceView();
    }


    private void initVoiceView() {

        initRecordManager();
    }


    Toast toast;





    /**
     * ������Ϣ��ʷ�������ݿ��ж���
     */
    private List<BmobMsg> initMsgData() {
        final List<BmobMsg> list = BmobDB.create(this).queryMessages(targetId,MsgPagerNum);

//        for(int i = 0 ; i < list.size(); i++){
//            BmobQuery<User> bmobQuery = new BmobQuery<User>();
//            String id = list.get(i).getBelongId();
//            bmobQuery.getObject(ChatActivity.this, id, new GetListener<User>() {
//                @Override
//                public void onSuccess(User object) {
//                    // TODO Auto-generated method stub
//                    avatar = object.getPicFilename();
//                    list.get(i).setBelongAvatar(avatar);
//                }
//
//                @Override
//                public void onFailure(int code, String msg) {
//                    // TODO Auto-generated method stub
//                    if (false) {
//                        avatar = null;
//                    }
//                }
//            });
//        }
//            list.get(i).setBelongAvatar(id2picfilename(list.get(i).getBelongId()));
        return list;
    }

    /**
     * ����ˢ��
     * @Title: initOrRefresh
     * @Description: TODO
     * @param
     * @return void
     * @throws
     */
    private void initOrRefresh() {
        if (mAdapter != null) {
            if (MyMessageReceiver.mNewNum != 0) {// ���ڸ��µ���������������ڼ�������Ϣ����ʱ�ٻص�����ҳ���ʱ����Ҫ��ʾ��������Ϣ
                int news=  MyMessageReceiver.mNewNum;//�п��������ڼ䣬����N����Ϣ,�����Ҫ������ʾ�ڽ�����
                int size = initMsgData().size();
                for(int i=(news-1);i>=0;i--){
                    mAdapter.add(initMsgData().get(size-(i+1)));// ������һ����Ϣ��������ʾ
                }
                mListView.setSelection(mAdapter.getCount() - 1);
            } else {
                mAdapter.notifyDataSetChanged();
            }
        } else {
            mAdapter = new MessageChatAdapter(this, initMsgData());
            mListView.setAdapter(mAdapter);
        }
    }

    private void initAddView() {
//		tv_picture = (TextView) findViewById(R.id.tv_picture);
//		tv_camera = (TextView) findViewById(R.id.tv_camera);
//		tv_location = (TextView) findViewById(R.id.tv_location);
//        tv_picture.setOnClickListener(this);
//        tv_location.setOnClickListener(this);
//        tv_camera.setOnClickListener(this);
    }

    private void initBottomView() {
        // �����
        btn_chat_add = (Button) findViewById(R.id.btn_chat_add);
        btn_chat_emo = (Button) findViewById(R.id.btn_chat_emo);
        btn_chat_add.setOnClickListener(this);
        btn_chat_emo.setOnClickListener(this);
        // ���ұ�
        btn_chat_keyboard = (Button) findViewById(R.id.btn_chat_keyboard);
        btn_chat_voice = (Button) findViewById(R.id.btn_chat_voice);
        btn_chat_voice.setOnClickListener(this);
        btn_chat_keyboard.setOnClickListener(this);
        btn_chat_send = (Button) findViewById(R.id.btn_chat_send);
        btn_chat_send.setOnClickListener(this);
        // ������
        layout_more = (LinearLayout) findViewById(R.id.layout_more);
        layout_emo = (LinearLayout) findViewById(R.id.layout_emo);
        layout_add = (LinearLayout) findViewById(R.id.layout_add);
        initAddView();

        // �����
        edit_user_comment = (EmoticonsEditText) findViewById(R.id.edit_user_comment);
        edit_user_comment.setOnClickListener(this);
        edit_user_comment.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // TODO Auto-generated method stub
                if (!TextUtils.isEmpty(s)) {
                    btn_chat_send.setVisibility(View.VISIBLE);
                    btn_chat_keyboard.setVisibility(View.GONE);
                    btn_chat_voice.setVisibility(View.GONE);
                } else {
                    if (btn_chat_voice.getVisibility() != View.VISIBLE) {
                        btn_chat_voice.setVisibility(View.VISIBLE);
                        btn_chat_send.setVisibility(View.GONE);
                        btn_chat_keyboard.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
            }
        });

    }



    MessageChatAdapter mAdapter;

    private void initXListView() {
        // ���Ȳ�������ظ���
        mListView.setPullLoadEnable(false);
        // ��������
        mListView.setPullRefreshEnable(true);
        // ���ü�����
        mListView.setXListViewListener(this);
        mListView.pullRefreshing();
        mListView.setDividerHeight(0);
        initOrRefresh();
        mListView.setSelection(mAdapter.getCount() - 1);
        mListView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                // TODO Auto-generated method stub
                hideSoftInputView();
                layout_more.setVisibility(View.GONE);
                layout_add.setVisibility(View.GONE);
                btn_chat_voice.setVisibility(View.VISIBLE);
                btn_chat_keyboard.setVisibility(View.GONE);
                btn_chat_send.setVisibility(View.GONE);
                return false;
            }
        });

        // �ط���ť�ĵ���¼�
        mAdapter.setOnInViewClickListener(R.id.iv_fail_resend,
                new MessageChatAdapter.onInternalClickListener() {

                    @Override
                    public void OnClickListener(View parentV, View v,
                                                Integer position, Object values) {
                        // �ط���Ϣ
                        resendTextMsg(parentV, values);
                    }
                });
    }


    /**
     *重发文本消息
     */
    private void resendTextMsg(final View parentV, final Object values) {
        BmobChatManager.getInstance(ChatActivity.this).resendTextMessage(
                targetUser, (BmobMsg) values, new PushListener() {

                    @Override
                    public void onSuccess() {
                        // TODO Auto-generated method stub
                        ShowLog("���ͳɹ�");
                        ((BmobMsg) values)
                                .setStatus(BmobConfig.STATUS_SEND_SUCCESS);
                        parentV.findViewById(R.id.progress_load).setVisibility(
                                View.INVISIBLE);
                        parentV.findViewById(R.id.iv_fail_resend)
                                .setVisibility(View.INVISIBLE);
                        parentV.findViewById(R.id.tv_send_status)
                                .setVisibility(View.VISIBLE);
                        ((TextView) parentV.findViewById(R.id.tv_send_status))
                                .setText("已发送");
                    }

                    @Override
                    public void onFailure(int arg0, String arg1) {
                        // TODO Auto-generated method stub
                        ShowLog("����ʧ��:" + arg1);
                        ((BmobMsg) values)
                                .setStatus(BmobConfig.STATUS_SEND_FAIL);
                        parentV.findViewById(R.id.progress_load).setVisibility(
                                View.INVISIBLE);
                        parentV.findViewById(R.id.iv_fail_resend)
                                .setVisibility(View.VISIBLE);
                        parentV.findViewById(R.id.tv_send_status)
                                .setVisibility(View.INVISIBLE);
                    }
                });
        mAdapter.notifyDataSetChanged();
    }



    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.edit_user_comment:// ����ı������
                mListView.setSelection(mListView.getCount() - 1);
                if (layout_more.getVisibility() == View.VISIBLE) {
                    layout_add.setVisibility(View.GONE);
                    layout_emo.setVisibility(View.GONE);
                    layout_more.setVisibility(View.GONE);
                }
                break;

            case R.id.btn_chat_send:// �����ı�
                final String msg = edit_user_comment.getText().toString();
                if (msg.equals("")) {
                    ShowToast("请输入发送消息!");
                    return;
                }
                boolean isNetConnected = util.CommonUtils.isNetworkAvailable(this);
                if (!isNetConnected) {
                    ShowToast(R.string.network_tips);
                    // return;
                }
                // ��װBmobMessage����
                BmobMsg message = BmobMsg.createTextSendMsg(this, targetId, msg);
                message.setBelongId(User.getCurrentUser(ChatActivity.this).getObjectId());
                message.setBelongAvatar(BmobChatUser.getCurrentUser(ChatActivity.this, User.class).getPicFilename());
                message.setExtra("Bmob");
                // Ĭ�Ϸ�����ɣ������ݱ��浽������Ϣ�������Ự����
                manager.sendTextMessage(targetUser, message, new PushListener(){

                    @Override
                    public void onSuccess() {
                        Toast.makeText(ChatActivity.this, "成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        Toast.makeText(ChatActivity.this, "失败"+i + s, Toast.LENGTH_SHORT).show();
                    }
                });
                // ˢ�½���
                refreshMessage(message);

                break;
        }
    }

    // ��ʾ�����
    public void showSoftInputView() {
        if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                        .showSoftInput(edit_user_comment, 0);
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // ����Ϣ�������ˢ�½���
        initOrRefresh();
        MyMessageReceiver.ehList.add(this);// �������͵���Ϣ
        // �п��������ڼ䣬������������֪ͨ������ʱ����Ҫ���֪ͨ�����δ����Ϣ��
        BmobNotifyManager.getInstance(this).cancelNotify();
        BmobDB.create(this).resetUnread(targetId);
        //�����Ϣδ����-���Ҫ��ˢ��֮��
        MyMessageReceiver.mNewNum=0;
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MyMessageReceiver.ehList.remove(this);// �������͵���Ϣ
//		// ֹͣ¼��
//		if (recordManager.isRecording()) {
//			recordManager.cancelRecording();
////			layout_record.setVisibility(View.GONE);
//		}
//		// ֹͣ����¼��
//		if (NewRecordPlayClickListener.isPlaying
////				&& NewRecordPlayClickListener.currentPlayListener != null) {
////			NewRecordPlayClickListener.currentPlayListener.stopPlayRecord();
////		}

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == NEW_MESSAGE) {
                BmobMsg message = (BmobMsg) msg.obj;
                String uid = message.getBelongId();
                final BmobMsg m = BmobChatManager.getInstance(ChatActivity.this).getMessage(message.getConversationId(), message.getMsgTime());
                if (!uid.equals(targetId))// ������ǵ�ǰ��������������Ϣ��������
                    return;
                BmobQuery<User> bmobQuery = new BmobQuery<User>();
                String id = m.getBelongId();
                bmobQuery.getObject(ChatActivity.this, id, new GetListener<User>() {
                    @Override
                    public void onSuccess(User object) {
                        // TODO Auto-generated method stub
                        avatar = object.getPicFilename();
                        m.setBelongAvatar(avatar);
                        mAdapter.add(m);
                        // ��λ
                        mListView.setSelection(mAdapter.getCount() - 1);
                        //ȡ����ǰ��������δ����ʾ
                        BmobDB.create(ChatActivity.this).resetUnread(targetId);

                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        // TODO Auto-generated method stub
                        if (false) {
                            avatar = null;
                        }
                    }
                });
            }
        }
    };

    public String id2picfilename(String id){
        BmobQuery<User> bmobQuery = new BmobQuery<User>();
        bmobQuery.getObject(this, id, new GetListener<User>() {
            @Override
            public void onSuccess(User object) {
                // TODO Auto-generated method stub
                avatar = object.getPicFilename();

            }

            @Override
            public void onFailure(int code, String msg) {
                // TODO Auto-generated method stub
                if(false){
                    avatar = null;
                }
            }
        });
        return avatar;
    }
    public static final int NEW_MESSAGE = 0x001;// �յ���Ϣ

    NewBroadcastReceiver  receiver;

    private void initNewMessageBroadCast(){
        // ע�������Ϣ�㲥
        receiver = new NewBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(BmobConfig.BROADCAST_NEW_MESSAGE);
        //���ù㲥�����ȼ������Mainacitivity,���������Ϣ����ʱ��������chatҳ�棬ֱ����ʾ��Ϣ����������ʾ��Ϣδ��
        intentFilter.setPriority(5);
        registerReceiver(receiver, intentFilter);
    }

    /**
     * ����Ϣ�㲥������
     *
     */
    private class NewBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String from = intent.getStringExtra("fromId");
            String msgId = intent.getStringExtra("msgId");
            String msgTime = intent.getStringExtra("msgTime");
            // �յ�����㲥��ʱ��message�Ѿ�����Ϣ���У���ֱ�ӻ�ȡ
            if(!TextUtils.isEmpty(from) && !TextUtils.isEmpty(msgId) && !TextUtils.isEmpty(msgTime)){
                BmobMsg msg = BmobChatManager.getInstance(ChatActivity.this).getMessage(msgId, msgTime);
                if (!from.equals(targetId))// ������ǵ�ǰ��������������Ϣ��������
                    return;
                //��ӵ���ǰҳ��
                mAdapter.add(msg);
                // ��λ
                mListView.setSelection(mAdapter.getCount() - 1);
                //ȡ����ǰ��������δ����ʾ
                BmobDB.create(ChatActivity.this).resetUnread(targetId);
            }
            // �ǵðѹ㲥���ս��
            abortBroadcast();
        }
    }

    /**
     * ˢ�½���
     * @Title: refreshMessage
     * @Description: TODO
     * @param @param message
     * @return void
     * @throws
     */
    private void refreshMessage(BmobMsg msg) {
        // ���½���
        mAdapter.add(msg);
        mListView.setSelection(mAdapter.getCount() - 1);
        edit_user_comment.setText("");
    }


    @Override
    public void onMessage(BmobMsg message) {
        // TODO Auto-generated method stub
        Message handlerMsg = handler.obtainMessage(NEW_MESSAGE);
        handlerMsg.obj = message;
        handler.sendMessage(handlerMsg);
    }

    @Override
    public void onNetChange(boolean isNetConnected) {
        // TODO Auto-generated method stub
        if (!isNetConnected) {
            ShowToast(R.string.network_tips);
        }
    }

    @Override
    public void onAddUser(BmobInvitation invite) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onOffline() {
        // TODO Auto-generated method stub
//		showOfflineDialog(this);
    }

    @Override
    public void onReaded(String conversionId, String msgTime) {
        // TODO Auto-generated method stub
        // �˴�Ӧ�ù��˵����Ǻ͵�ǰ�û�������Ļ�ִ��Ϣ�����ˢ��
        if (conversionId.split("&")[1].equals(targetId)) {
            // �޸Ľ�����ָ����Ϣ���Ķ�״̬
            for (BmobMsg msg : mAdapter.getList()) {
                if (msg.getConversationId().equals(conversionId)
                        && msg.getMsgTime().equals(msgTime)) {
                    msg.setStatus(BmobConfig.STATUS_SEND_RECEIVERED);
                }
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    public void onRefresh() {
        // TODO Auto-generated method stub
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                MsgPagerNum++;
                int total = BmobDB.create(ChatActivity.this).queryChatTotalCount(targetId);
                BmobLog.i("��¼������" + total);
                int currents = mAdapter.getCount();
                if (total <= currents) {
                    ShowToast("聊天记录加载完了哦!");
                } else {
                    List<BmobMsg> msgList = initMsgData();
                    mAdapter.setList(msgList);
                    mListView.setSelection(mAdapter.getCount() - currents - 1);
                }
                mListView.stopRefresh();
            }
        }, 1000);
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (layout_more.getVisibility() == View.VISIBLE) {
                layout_more.setVisibility(View.GONE);
                return false;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        hideSoftInputView();
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {
        }

    }

}
